//
//  ComposeViewController.swift
//  TYHWeibo
//
//  Created by IOS on 15/8/9.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
import SVProgressHUD
private let kStatusTextMaxLength = 10

class ComposeViewController: UIViewController, UITextViewDelegate {

    private lazy var emoticonVc: emoticonViewController = emoticonViewController {[weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    
    //懒加载照片选择器
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
    
    
    //关闭？
    func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func sendStatus() {
//        print("发布消息")
        let text = textView.emoticonText
        if text.characters.count > kStatusTextMaxLength {
        SVProgressHUD.showInfoWithStatus("输入的文本过长", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        let image = photoSelectorVC.photos.last
        
        NetworkTools.sharedTools.sendStatus(textView.emoticonText, image: image) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Gradient)
            }
            self.close()
        }
    }
    
    func inputEmotion() {
        print("选择表情")
        
        //注销键盘通知
        removeKeyboardOberserver()
        
        //关闭键盘
        textView.resignFirstResponder()
        //设置输入键盘
        textView.inputView = (textView.inputView == nil) ? emoticonVc.view : nil
        
        //重新注册通知
        addKeyboardOberserver()
        //重新 激活键盘
        textView.becomeFirstResponder()
        
    }
    //UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //计算用户输入的完整长度，并提示用户
        let text = textView.emoticonText
        
        let len = kStatusTextMaxLength - text.characters.count
        
        lengthTipLabel.text = "\(len)"
        
        lengthTipLabel.textColor = len > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        addKeyboardOberserver()
        // Do any additional setup after loading the view.
    }
    
    deinit {
        removeKeyboardOberserver()
    }
    
    ///添加键盘通知
    private func addKeyboardOberserver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    ///删除键盘通知
    private func removeKeyboardOberserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //toolbar约束
    var toolbarBottomCons: NSLayoutConstraint?
    //键盘监听方法
    func keyboardChanged(n: NSNotification) {
        print(n)
        //获取目标frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //动画时间
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        //设置约束
        toolbarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        //动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func loadView() {
        super.loadView()
        
        view.addSubview(textView)
        view.addSubview(photoSelectorVC.view)
        view.addSubview(toolbar)
        
        //添加子控制器
        addChildViewController(photoSelectorVC)
        
        prepareNav()
        prepareToolbar()
        prepareTextView()
        preparePhotoSelectorView()
    }
    
    //准备图片选择器
    func preparePhotoSelectorView() {
        
        
        //自动布局
        var s = UIScreen.mainScreen().bounds.size
        s.height *= 0.6
        
        photoSelectorVC.view .ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
    }
    
    ///准备文本框
    func prepareTextView() {
        
        textView.backgroundColor = UIColor.whiteColor()
        
        // 提示：在 iOS 开发中，如果是单纯的 nav + scrollView 会自动调整滚动视图的边距
//        // 会将顶部的导航栏的高度预留出来，就能实现滚动视图穿透效果
//        textView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        
        //添加占位标签
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
        view.addSubview(lengthTipLabel)
        lengthTipLabel.text = String(kStatusTextMaxLength)
        lengthTipLabel.sizeToFit()
        lengthTipLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
    }
    
    func prepareToolbar() {
//        let toolbar = UIToolbar()
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
       
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        //底部约束
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action": "inputEmotion"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
//            let btn = UIButton()
//            btn.setImage(UIImage(named: dict["imageName"]!), forState: UIControlState.Normal)
//            btn.setImage(UIImage(named: dict["imageName"]! + "_highlighted"), forState: UIControlState.Highlighted)
//            btn.sizeToFit()
            
//            if let actionName = dict["action"] {
//                btn.addTarget(self, action: Selector(actionName), forControlEvents: UIControlEvents.TouchUpInside)
            
//            }
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            
//            let item = UIBarButtonItem(customView: btn)
            
//            items.append(item)
            //最佳弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        
        }
        //移除最后一个
        items.removeLast()
        //
        toolbar.items = items
        
    }
    
    func prepareNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题栏
        let titleView = UIView(frame: CGRectMake(0, 0, 200, 32))
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 13)
        nameLabel.text = UserAccount.sharedAccount?.name ?? ""
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
        
    }
    
    ///懒加载
    private lazy var textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.delegate = self
        //允许垂直下拉
        textView.alwaysBounceVertical = true
        //拖拽关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return textView
    }()
    
    private lazy var placeholderLabel: UILabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    
    private lazy var toolbar = UIToolbar()
    
    private lazy var lengthTipLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 12)
}








